<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

use Request;
use Hash;
class User extends Model
{


  public function has_password_and_username()
  {
    $username = Request::get('username');
    $password = Request::get('password');
       if ($username && $password)
       return [$username,$password];
       else
       return false;
  }
  /* regiest api*/
  public function signup()
  {

  $haspassword_andusername = $this->has_password_and_username();

      if (!$haspassword_andusername) {
        return ['status'=>0, 'msg'=>'username and password not null'];

      }
      $username = $haspassword_andusername[0];
      $password = $haspassword_andusername[1];
     /* 判断用户是否存在*/
      $user_exits =$this
        ->where('username',$username)
        ->exists();
        if($user_exits)
        return ['status'=>0,'msg'=>'username is exitsts'];




       $hash_paswword = bcrypt($password);

       $user= $this;
       $user->password = $hash_paswword;
       $user->username  =  $username;
       if ($user->save())
            return ['status'=>1,'id'=> $user->id];
      else {
          return ['status'=>'0','msg'=>'db insert failuer'];
      }
    }

  /* 用户登录api*/
   public function login()
   {
        $haspassword_andusername = $this->has_password_and_username();

         if (!$haspassword_andusername) {
           return ['status'=>0, 'msg'=>'username and password not null'];
        }
        $username = $haspassword_andusername[0];
        $password = $haspassword_andusername[1];

        $user=$this->where('username',$username)->first();
        if(!$user)
          return ['status'=>0,'msg'=>'user not is_exits'];

          $hashpasword =$user->password;
          if(!Hash::check($password,$hashpasword)){
            return ['status'=>0 ,'msg'=>'password error'];
          }else{
        /*将用户信息写入session*/
            session()->put('username',$user->username);
            session()->put('user_id',$user->id);

            return ['status'=>1,'user_id'=>$user->id];
          }

    }

    public function is_logged_in()
    {
      return session('user_id') ?: 0;
    }

    public function  logout()
    {
      session()->forget('username');
      session()->forget('user_id');

      return ['status'=>1];
    }

    public function answer()
    {
      return $this->belongsToMany('App\Http\Models\Answer')
      ->withPivot('vote')
      ->withTimestamps();
    }




}
